package com.wxtwxt.ruralmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wxtwxt.ruralmall.common.constant.ProductConstant;
import com.wxtwxt.ruralmall.product.entity.AttrAttrgroupRelationEntity;
import com.wxtwxt.ruralmall.product.entity.AttrGroupEntity;
import com.wxtwxt.ruralmall.product.entity.CategoryEntity;
import com.wxtwxt.ruralmall.product.service.AttrAttrgroupRelationService;
import com.wxtwxt.ruralmall.product.service.AttrGroupService;
import com.wxtwxt.ruralmall.product.service.CategoryService;
import com.wxtwxt.ruralmall.product.vo.AttrGroupWithAttrsVo;
import com.wxtwxt.ruralmall.product.vo.AttrResponseVo;
import com.wxtwxt.ruralmall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxtwxt.ruralmall.common.utils.PageUtils;
import com.wxtwxt.ruralmall.common.utils.Query;

import com.wxtwxt.ruralmall.product.dao.AttrDao;
import com.wxtwxt.ruralmall.product.entity.AttrEntity;
import com.wxtwxt.ruralmall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<AttrEntity> getAttrRelation(Long attrgroupId) {
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationService.list(queryWrapper.eq("attr_group_id", attrgroupId));
        if(entities.size() > 0) {
            List<Long> attrIds = entities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
            return baseMapper.selectBatchIds(attrIds);
        }
        return null;
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.save(attrEntity);
        if (Objects.equals(attrVo.getAttrType(), ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) && attrVo.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelation.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationService.save(attrAttrgroupRelation);
        }
    }

    @Override
    public PageUtils queryBaseAttrList(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", type.equalsIgnoreCase(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getMsg()) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> pageRecords = page.getRecords();
        if (pageRecords.size() > 0) {
            List<AttrResponseVo> resultList = pageRecords.stream().map(attrEntity -> {
                AttrResponseVo attrResponseVo = new AttrResponseVo();
                BeanUtils.copyProperties(attrEntity, attrResponseVo);
                CategoryEntity categoryEntity = categoryService.getOne(new QueryWrapper<CategoryEntity>().eq("cat_id", attrEntity.getCatelogId()));
                if (categoryEntity != null) {
                    attrResponseVo.setCatelogName(categoryEntity.getName());
                }
                if (type.equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getMsg())) {
                    AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                    if (relationEntity != null) {
                        AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                        attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
                return attrResponseVo;
            }).collect(Collectors.toList());
            pageUtils.setList(resultList);
        }
        return pageUtils;
    }

    @Override
    public AttrResponseVo getAttrInfo(Long attrId) {
        AttrResponseVo attrResponseVo = new AttrResponseVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrResponseVo);
        // 所属分组信息
        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (relationEntity != null) {
            attrResponseVo.setAttrGroupId(relationEntity.getAttrGroupId());
            AttrGroupEntity groupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
            if (groupEntity != null) {
                attrResponseVo.setGroupName(groupEntity.getAttrGroupName());
            }
        }
        CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
        if (categoryEntity != null) {
            // 获取分类路径
            Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
            attrResponseVo.setCatelogPath(catelogPath);
            attrResponseVo.setCatelogName(categoryEntity.getName());
        }
        return attrResponseVo;
    }

    @Override
    public void updateAttrVo(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);
        if (Objects.equals(attrVo.getAttrType(), ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
            long attrGroupCount = attrAttrgroupRelationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if(attrVo.getAttrGroupId() != null) {
                if (attrGroupCount > 0) {
                    UpdateWrapper<AttrAttrgroupRelationEntity> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("attr_group_id", attrVo.getAttrGroupId()).eq("attr_id", attrVo.getAttrId());
                    attrAttrgroupRelationService.update(updateWrapper);
                } else {
                    AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
                    attrAttrgroupRelation.setAttrId(attrEntity.getAttrId());
                    attrAttrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());
                    attrAttrgroupRelationService.save(attrAttrgroupRelation);
                }
            }else {
                attrAttrgroupRelationService.remove(new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            }
        }
    }

    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long attrgroupId) {
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.list(null);
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(relationEntities.size() > 0) {
            List<Long> attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
            wrapper.notIn("attr_id", attrIds);
        }

        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> w.eq("attr_id", key).or().like("attr_name", key));
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrs(Long catelogId) {
        QueryWrapper<AttrGroupEntity> queryWrapper = new QueryWrapper<>();
        List<AttrGroupEntity> attrGroupEntities = attrGroupService.list(queryWrapper.eq("catelog_id", catelogId));
        return attrGroupEntities.stream().map(attrGroupEntity -> {
            AttrGroupWithAttrsVo attrGroupWithAttrsVo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(attrGroupEntity, attrGroupWithAttrsVo);
            List<AttrEntity> attrEntities = this.getAttrRelation(attrGroupEntity.getAttrGroupId());
            attrGroupWithAttrsVo.setAttrs(attrEntities);
            return attrGroupWithAttrsVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<Long> getSearchTypeId(List<Long> attrIds) {
        return baseMapper.getSearchTypeId(attrIds);
    }

}